[JavaScript] Create a canvas artboard-summary (1)

Source: Internet
Author: User

Create a canvas artboard

Project Link: GitHub

Project preview: Github Pages

Project Description: Create a canvas artboard with basic functionality (including painting, eraser, save, etc.) through the tutorials and APIs provided with MDN.

In the course of the tutorial, master the basic usage of canvas and some places to be aware of.

Start creating a piece of artboard

First, we're going to create a canvas in HTML

<canvas id="canvas" width="300" height="300"></canvas>

This allows us to create an artboard with a wide height of 300*300px on the page.

However, such a small piece of drawing board, probably not enough we draw a little piggy page, we want the artboard to become a little bigger, preferably a full-screen artboard, how to set it?

First we can take a look at the description of the canvas size in MDN:

<canvas> looks like the element, and the only difference is that it doesn't have the SRC and ALT attributes. In fact the,<canvas> tag has only two attributes--width and height. These are optional and are also set using DOM properties. When the width and height are not set, the canvas initializes a width of 300 pixels and a height of >150 pixels. The element can use CSS to define the size, but the image will stretch to fit its frame size when it is drawn: if the size of the CSS is not the same as the original canvas, it will appear distorted.

According to the information provided by the MDN, we can know that, as far as possible not to recommend the use of CSS directly, then we can use this scenario: using JavaScript to control the canvas's wide height

var pageWidth = document.documentElement.clientWidthvar pageHeight = document.documentElement.clientHeightcanvas.width = pageWidthcanvas.height = pageHeight

This allows you to set the canvas size to full screen.
But it doesn't look very good, let's optimize it and encapsulate it as a function:

setCanvasSize()function setCanvasSize(canvas) {    function pageSize(){        // 设置canvas的宽高为全屏        var pageWidth = document.documentElement.clientWidth        var pageHeight = document.documentElement.clientHeight        canvas.width = pageWidth        canvas.height = pageHeight    }        pageSize()        // 当用户拉伸窗口时,改变canvas的宽高    window.onresize = function() {        pageSize()    }}

After the artboard is created, Next:

Listen to the user's mouse action first according to the steps of the tutorial to get the rendering context and its painting function
var canvas = document.getElementById(‘canvas‘)var ctx = canvas.getContext(‘2d‘)
Determine the painting function and wrap it up as a function
function drawLine(x1, y1, x2, y2) {    // 开始绘画动作      ctx.beginPath()    //黄色的线    ctx.strokeStyle = "yellow"    // 绘画的开始坐标    ctx.moveTo(x1, y1)    // 绘画路径的宽度    ctx.lineWidth = 2    // 绘画的结束坐标    ctx.lineTo(x2, y2)    ctx.stroke()    // 绘画结束    ctx.closePath()}
Create a tag to determine the user's mouse click state (if Fales, the mouse is released; If true, the mouse is pressed)
var using = false
Create an eraser, trigger events when clicked, cannot paint, can only erase
<button id="eraser">橡皮檫</button>
var eraserEnabled = falseeraser.onclick = function() {    eraserEnabled = true}
Create functions to monitor different states of the mouse, and to determine whether to paint according to the state
Listentomouse (canvas,ctx) function listentomouse (canvas, CTX) {//Determine the user clicks the moment coordinates var lastpoint = {x:undefined, y:und efined}//Draw Circle function Drawcir (x, y, radius) {Ctx.beginpath () Ctx.arc (x, y, radius, 0,.) c        Tx.fill ()}//Draw line function DrawLine (x1, y1, x2, y2,) {Ctx.beginpath () Ctx.strokestyle = "Yellow"    Ctx.moveto (x1, y1) Ctx.linewidth = 2 Ctx.lineto (x2, y2) ctx.stroke () Ctx.closepath ()        } Canvas.onmousedown = function (KeyWord) {var x = Keyword.clientx;        var y = keyword.clienty; if (eraserenabled) {using = True Ctx.clearrect (x, Y, Ten)} else {//Determine what the user is doing at this point            The coordinates of the strike coordinate with the next point using = true; Lastpoint = {x:x, y:y} drawcir (x, Y, 2)}} canvas.onmousemove = function (KeyWord) {V        Ar x = keyword.clientx;        var y = keyword.clienty; if (eraserenabled) {if (using) {ctx.clearrect (x, Y, 10, 10)}}                else {if (using) {var newpoint = {x:x, y:y} drawcir (x, Y, 2)            DrawLine (Lastpoint.x, Lastpoint.y, Newpoint.x, NEWPOINT.Y)//This sentence is very important lastpoint = Newpoint }}} Canvas.onmouseup = function (KeyWord) {using = false}}
The artboard has been basically completed, we have to add a "brush" button for the artboard, so that the user can switch, the logic implementation is also more smooth (when the user click on the "brush" to paint, click "Eraser" can be erased)
<div id="action" class="action">    <button id="eraser">橡皮檫</button>    
//启用橡皮擦/画笔var eraserEnabled = falseeraser.onclick = function() {    eraserEnabled = true    action.className = "action x"}brush.onclick = function() {    eraserEnabled = false    action.className = "action"}

The basic functions of our canvas have been realized!

Next you can think of him as perfecting more features.

[JavaScript] Create a canvas artboard-summary (1)

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.