search
HomeWeb Front-endH5 TutorialCanvas Game Development Learning Part 4: Applying Images

One of the interesting features of Canvas is that it can introduce images, which can be used for picture synthesis or background creation. Currently, only text can be added to images (the standard description does not include the function of drawing text). As long as the images supported by Gecko (such as PNG, GIF, JPEG, etc.) can be introduced into canvas, other canvas elements can also be used as the source of images.

Introducing images importing images

Introducing images only requires two simple steps:

The first is of course the source image, not a simple URL path, but it can be a JavaScript Image object reference, or other canvas element.

Then use the drawImage method to insert the image into the canvas.

Let’s take a look at the first step. There are basically four options:

Referring to the images on the page Using images which are on the same page

We can Get the images on the page through the document.images collection, the document.getElementsByTagName method, or the document.getElementById method (if the ID of the image element is known).

Using other canvas elements Using other canvas elements is similar to referencing images on the page, using the document.getElementsByTagName or document.getElementById method to obtain other canvas elements. But what you introduce should be a prepared canvas. A common application is to create thumbnails for another large canvas.

Creating an image from scratch

Alternatively, we can use a script to create a new Image
object, but the main disadvantage of this method is that if you do not want the script Pausing while waiting for image installation requires breaking through preloading. We can create images through the following simple method:

var img = new Image();   // Create new Image object  
  img.src = 'myImage.png'; // Set source path


When the script is executed, the image starts to load. If the image is not loaded when drawImage is called, the script will wait until it is loaded. If you don't want this, you can use the onload
event:

var img = new Image();   // Create new Image object  
  img.onload = function(){  
    // executedrawImage statements here  
  }  
  img.src = 'myImage.png'; // Set source path

If you only use one image, this is enough. But once more than one image is needed, more complex processing methods are required, but the image preloading strategy is beyond the scope of this tutorial. If you are interested, you can refer to JavaScript Image Preloader.

Embedding an image via data: url Embedding an image via data: url

We can also reference images through data: url. Data urls allow an image to be defined as a Base64 encoded string. The advantage is that the image content is available immediately, without having to go back to the server. (Another advantage is that CSS, JavaScript, HTML and images can all be encapsulated together, making migration very convenient.) The disadvantage is that images cannot be cached. If the image is large, the embedded url data will be quite long:

var img_src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7
qyrIXiGBYAOw==';

drawImage

Once we obtain the source image object, we can use the drawImage method to render it into the canvas. The drawImage method has three forms, the following is the most basic one.

drawImage(image, x, y)

Where image is an image or canvas object, x and y are its starting coordinates in the target canvas.


drawImage
Example 1

In the following example I use an external image as the background of a linear graphic. Using a background image we don't need to draw the responsible background, saving a lot of code. Only one image object is used here, so the drawing action is triggered in its onload
event response function. The drawImage
method places the background image at the upper left corner of the canvas (0,0).

Canvas Game Development Learning Part 4: Applying Images

function draw() {  
 var ctx = document.getElementById('canvas').getContext('2d');  
 var img = new Image();  
 img.onload = function(){  
 ctx.drawImage(img,0,0);  
 ctx.beginPath();  
 ctx.moveTo(30,96);  
 ctx.lineTo(70,66);  
 ctx.lineTo(103,76);  
 ctx.lineTo(170,15);  
 ctx.stroke();  
 }  
 img.src = 'images/backdrop.png';  
 }

缩放Scaling

drawImage
方法的又一变种是增加了两个用于控制图像在 canvas 中缩放的参数。

drawImage(image, x, y, width, height)

切片Slicing

drawImage方法的第三个也是最后一个变种有8个新参数,用于控制做切片显示的。

drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

第一个参数和其它的是相同的,都是一个图像或者另一个 canvas 的引用。其它8个参数最好是参照下边的图解,前4个是定义图像源的切片位置和大小,后4个则是定义切片的目标显示位置和大小。

Canvas Game Development Learning Part 4: Applying Images

Canvas Game Development Learning Part 4: Applying Images

切片是个做图像合成的强大工具。假设有一张包含了所有元素的图像,那么你可以用这个方法来合成一个完整图像。例如,你想画一张图表,而手上有一个包含所有 必需的文字的 PNG 文件,那么你可以很轻易的根据实际数据的需要来改变最终显示的图表。这方法的另一个好处就是你不需要单独装载每一个图像。

drawImage
示例2

Canvas Game Development Learning Part 4: Applying Images

在这个例子里面我用到上面已经用过的犀牛图像,不过这次我要给犀牛头做个切片特写,然后合成到一个相框里面去。相框带有阴影效果,是一个以 24-bit PNG 格式保存的图像。我用一个与上面用到的不同的方法来装载图像,直接将图像插入到 HTML 里面,然后通过 CSS 隐藏(display:none)它。两个图像我都赋了id,方便后面使用。看下面的脚本,相当简单,首先犀牛头做好切片(第一个drawImage)放在 canvas 上,然后再上面套个相框(第二个drawImage)。

function draw() {  
   var canvas = document.getElementById('canvas');  
   var ctx = canvas.getContext('2d');  
   
   // Draw slice  
   ctx.drawImage(document.getElementById('source'),  
                 33,71,104,124,21,20,87,104);  
   
   // Draw frame  
   ctx.drawImage(document.getElementById('frame'),0,0);  
 }


示例:画廊 Art gallery example

Canvas Game Development Learning Part 4: Applying Images

我这一章最后的示例是弄一个小画廊。画廊由挂着几张画作的格子组成。当页面装载好之后,为每张画创建一个 canvas 元素并用加上画框然后插入到画廊中去。在我这个例子里面,所有“画”都是固定宽高的,画框也是。你可以做些改进,通过脚本用画的宽高来准确控制围绕它的画框的大小。下面的代码应该是蛮自我解释的了。就是遍历图像对象数组,依次创建新的 canvas 元素并添加进去。可能唯一需要注意的,对于那些并不熟悉 DOM 的朋友来说,是 insertBefore 方法的用法。insertBefore是父节点(单元格)的方法,用于将新节点(canvas 元素)插入到我们想要插入的节点之前

function draw() {  
     
     // Loop through all images  
     for (i=0;i<document.images.length;i++){  
     
       // Don&#39;t add a canvas for the frame image  
       if (document.images[i].getAttribute(&#39;id&#39;)!=&#39;frame&#39;){  
     
         // Create canvas element  
         canvas = document.createElement(&#39;CANVAS&#39;);  
         canvas.setAttribute(&#39;width&#39;,132);  
         canvas.setAttribute(&#39;height&#39;,150);  
     
         // Insert before the image  
         document.images[i].parentNode.insertBefore(canvas,document.images[i]);  
     
         ctx = canvas.getContext(&#39;2d&#39;);  
     
         // Draw image to canvas  
         ctx.drawImage(document.images[i],15,20);  
     
         // Add frame  
         ctx.drawImage(document.getElementById(&#39;frame&#39;),0,0);  
       }  
     }  
   }

以上就是canvas游戏开发学习之四:应用图像的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software