Use javascript + html5 to draw images on webpages

Source: Internet
Author: User

This is a simple drawing application implemented on canvas using javascript. You can draw images in the following area using a html5-supported Browser:

Your browser does not support canvas!

The function is very simple. The principle is similar to that of drag-and-drop. There are mainly three events:

1. Bind The mousedown event to the canvas to mark the start of the painting (call moveTo to move the paint brush)

2. Bind The mousemove event to the document to process the painting behavior (call lineTo and stroke for painting)

3. Bind The mouseup event on the document to mark the end of the painting (unbind two events on the document)

Note how to pass the correct coordinate value when calling the moveTo and lineTo methods. The coordinate value should be the offset of the cursor relative to the upper left corner of the canvas, when obtaining the image, you need to consider the position of the canvas relative to the current view. The getBoundingClientRect method is useful (this method should be implemented by browsers that support HTML5). Finally, the clientX of the event object is used, clientY minus left and top returned by the getBoundingClientRect method.

In this way, a simple mouse painting function is completed, and there are also shortcomings, such as the inability to draw points... I personally think it is still relatively weak to use canvas for drawing, and complicated functions are not very easy to implement. However, you can try to add a method to save the image, for example, define Draw. prototype. save = function (){...}, you can call the toDataURL method.

Here is a good HTML5 canvas tutorial for beginners to learn ~

<! DOCTYPE html> 

Tip: valid only for IE9, Chrome, and Firefox!

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: info-contact@alibabacloud.com 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.