Use the drawImage method of Canvas, canvasdrawimage

Source: Internet
Author: User

Use the drawImage method of Canvas, canvasdrawimage

Canvas is a new element in html5. this element can be used to draw images through JavaScript. For example, you can use it to draw images, synthesize images, and make some animations.

Generally, we use an Image object to draw images on a canvas. Basically, some typical image formats (png, jpg, and gif) are correct. Okay, then let's use it.


1  var canvas=document.getElementById("game_canvas");2  var cxt=image.getContext("2d");3  var image=new Image();4  img.src="./res/background.jpg";

This is part of my code for a recent project. to render this background image to a canvas, you must use the drawImage method. The format of this method is as follows:


The first parameter is the image object to be cropped, and s represents the source, that is, the meaning of "source material. D Represents the dest, that is, the layout on the canvas. Sx and sy are the starting point for image cropping. sWidth and sHeight are the image cropping sizes. It is worth mentioning that I tried to use the percentage and found it was not feasible. Dx and dy are the positions in the upper left corner of the cropped image and the upper left corner of the canvas. dWidth and dHeight represent the scaled size. This product seems to only accept pixels as units. For example, the size of the image below is 800*600.


I perform the following operations on it:


First, I cropped it completely, and then scaled it to 200,400. When measured in the browser, it became


That is to say, it forcibly scales the width and height to 200*400, even if the image has been deformed.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.