Home > Web Front-end > H5 Tutorial > body text

Canvas Game Development Learning Part 4: Applying Images

黄舟
Release: 2017-01-16 17:45:47
Original
1415 people have browsed it

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
Copy after login


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
Copy after login

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==';
Copy after login

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)
Copy after login

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';  
 }
Copy after login

缩放Scaling

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

drawImage(image, x, y, width, height)
Copy after login

切片Slicing

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

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

第一个参数和其它的是相同的,都是一个图像或者另一个 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);  
 }
Copy after login


示例:画廊 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);  
       }  
     }  
   }
Copy after login

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


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template