Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to set up the artboard through canvas by html5

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how html5 sets up the artboard through canvas, which has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article.

I. Project introduction

Name: wisdom drawing board

Technology stack: HTML5,CSS3,JavaScript, mobile

Function description:

Support PC and mobile online drawing function

Realize the painting functions such as arbitrarily selecting brush color, adjusting brush thickness and erasing eraser.

Realize the local saving function of online drawing board

Support for undo and return operations

Custom background color

Second, the demonstration of project effect

Project address Preview address

Preview map

Preview of the PC side:

Preview of the mobile terminal:

After reading the preview above and experiencing the wisdom drawing board, I think it's OK. Remember to like it. No matter whether you are very excited or not, I am very excited. After all, I realized the project effect by myself. I was very proud and said a lot of nonsense. Below, you can start to knock on the code to achieve the effect you want!

Note: the following implementation of the project effect is mainly about JavaScript, the following is only to provide implementation ideas of the code, not all of the code.

Third, realize the project effect step by step

(1) Analysis page

Through the use case diagram, we know what functions users have to access our website.

What the user can do:

Draw pictures

Change the thickness of the brush

Toggle the color of the brush

Use an eraser to erase unwanted parts

Empty the drawing board

Save what you draw as a picture.

Perform undo and redo operations

Toggle artboard background color

Compatible with mobile (support for touch)

(2) HTML layout

When I write html, I introduce css file and js file.

The smart drawing board chooses the background color:

Pen size

Pen color

Opacity

(3) beautify the interface with CSS

Css code can beautify the interface according to personal habits, so instead of writing css code here, you can look at the project code directly or review the elements from the developer's tools. If you have any questions, you can talk to me in private. I don't think it's a big problem.

(4) use JS to realize the specific functions of the project.

1. Preparatory work

First of all, prepare a container, that is, the drawing board, the front html has already written this container, this is pure nonsense.

Then initialize the js

Let canvas = document.getElementById ('canvas'); let context = canvas.getContext (' 2d')

I'm going to make the drawing board full-screen, so next set the width and height of the canvas

Let pageWidth = document.documentElement.clientWidth;let pageHeight = document.documentElement.clientHeight;canvas.width = pageWidth;canvas.height = pageHeight

Since some IE do not support canvas, if we want to be compatible with IE, we can create a canvas and initialize it with excanvas. For IE plus exCanvas.js, we explicitly do not consider IE here.

But I make changes to the browser window on my computer, and the artboard doesn't zoom in adaptively. Solution:

/ / remember to execute the function autoSetSize, oh function autoSetSize () {canvasSetSize (); / / when executing this function, you will first set the width and height of canvas function canvasSetSize () {let pageWidth = document.documentElement.clientWidth; let pageHeight = document.documentElement.clientHeight; canvas.width = pageWidth; canvas.height = pageHeight } / / after the window size changes, the resize event will be triggered to reset the width and height of the canvas _ window.onresize = function () {canvasSetSize ();}}

two。 Realize the function of painting

The idea is to monitor mouse events and draw the recorded data with the drawLine () method.

Initialize the brush state of the current artboard, painting = false.

When the mouse is pressed (mousedown), the painting is set to true, indicating that the mouse is being drawn and the mouse is not released. Record the mouse click.

When the mouse is pressed, the mouse movement (mousemove) records the dots and draws them. If the mouse moves too fast, the browser can't keep up with the drawing speed, and there will be a gap between the points, so we need to connect the drawn points with a line (lineTo ()).

When the mouse is released (mouseup), set painting to false.

Note: drawCircle this method actually does not have to write, this is just so that you can understand where to click at the beginning?

Function listenToUser () {/ / define a variable to initialize the brush state let painting = false; / / record the last position of the brush let lastPoint = {x: undefined, y: undefined}; / / mouse down event canvas.onmousedown = function (e) {painting = true; let x = e.clientX; let y = e.clientY LastPoint = {'xprecarianghezzy}; drawCircle (xrecedence 5);} / / Mouse movement event canvas.onmousemove = function (e) {if (painting) {let x = e.clientX; let y = e.clientY; let newPoint = {' xcopyric DrawLine (lastPoint.x, lastPoint.y, newPoint.x, newPoint.y); lastPoint = newPoint;}} / / Mouse release event canvas.onmouseup = function () {painting = false;}} / / draw a point function function drawCircle {/ / create a new path, after generation, the graphics drawing command is directed to the path to generate the path. Context.beginPath (); / / draw an arc (circle) with the radius of radius at the center of the circle, / / from startAngle to the end of endAngle, and generate it in the direction given by anticlockwise (clockwise by default). Context.arc (xrecoveryGravity radiusre0pl Math.PIQ2); / / generate a solid graph context.fill () by filling the content area of the path; / / the graphics drawing command points back to the context after closing the path. Context.closePath ();} function drawLine (x1magentin x2jiny2) {/ / set the line width context.lineWidth = 10; / / set the line end style. Context.lineCap = "round"; / / sets the style where the line meets the line indirectly context.lineJoin = "round"; / / moveTo (XMague y) moves the stroke to the specified coordinates x and y (context.moveTo (x1Magne y1); / / lineTo (XMague y) draws a straight line context.lineTo (x2Powery2) from the current position to the specified x and y position / / draw graphic outlines through lines context.stroke (); context.closePath ();}

3. Realize the function of eraser

The idea of realization is:

Get the eraser element

Set the eraser initial state, eraserEnabled = false.

Monitor the eraser click event, click the eraser, change the eraser state, eraserEnabled = true, and switch class to achieve the activated effect.

When eraserEnabled is true, move the mouse to implement the rubber sassafras with context.clearRect ().

But I found that in the API of canvas, the one that can clear pixels is the clearRect method, but the clear area of the clearRect method is rectangular, after all, the eraser in most people's habits is round, so I introduced the powerful function of the clip region, that is, the clip method. The following code implements the rubber sassafras using context.clearRect (). Please see the treading pit section to learn how to better realize the rubber sassafras.

Let eraser = document.getElementById ("eraser"); let eraserEnabled = false;// remember to execute the function listenToUser () function listenToUser () {/ /. It means omitting the previously written code / /... / mouse down event canvas.onmousedown = function (e) {/ /. If (eraserEnabled) {/ / to use eraser context.clearRect {/ / to use the eraser context.clearRect {lastPoint = {'x _ ray _ 5} / / mouse movement event canvas.onmousemove = function (e) {let x = e.clientX; let y = e.clientY If (! painting) {return} if (eraserEnabled) {context.clearRect);} else {var newPoint = {'x copyright lastPoint.y,newPoint.x, newPoint.y); lastPoint = newPoint Click on the rubber sassafras eraser.onclick = function () {eraserEnabled = true; eraser.classList.add ('active'); brush.classList.remove (' active');}

4. Realize the function of screen cleaning

The idea of realization is:

Gets the element node.

Click the clear button to empty the canvas canvas.

Let reSetCanvas = document.getElementById ("clear"); / / clear the screen reSetCanvas.onclick = function () {ctx.clearRect ('white');} / reset the canvas background color function setCanvasBg (color) {ctx.fillStyle = color; ctx.fillRect;}

5. Realize the function of saving as a picture

The idea of realization is:

Get canvas.toDateURL

Create and insert an a tag in the page

A tag href equals canvas.toDateURL and add the download attribute

Click the save button, and the a tag triggers the click event

Let save = document.getElementById ("save"); / / download picture save.onclick = function () {let imgUrl = canvas.toDataURL ('image/png'); let saveA = document.createElement (' a'); document.body.appendChild (saveA); saveA.href = imgUrl; saveA.download = 'mypic'+ (new Date). GetTime (); saveA.target =' _ blank'; saveA.click ();}

6. Realize the function of changing the background color

The idea of realization is:

Get the corresponding element node.

Add a click event to the label where each class is bgcolor-item, and change the background color when the click event is triggered.

Click outside the div where the background color is set to hide that div.

Let selectBg = document.querySelector ('.bg-btn'); let bgGroup = document.querySelector (' .color-group'); let bgcolorBtn = document.querySelectorAll ('.bgcolor-item'); let penDetail = document.getElementById ("penDetail"); let activeBgColor =' # fff';// enables switching background color for (let I = 0; I)

< bgcolorBtn.length; i++) { bgcolorBtn[i].onclick = function (e) { // 阻止冒泡 e.stopPropagation(); for (let i = 0; i < bgcolorBtn.length; i++) { bgcolorBtn[i].classList.remove("active"); this.classList.add("active"); activeBgColor = this.style.backgroundColor; setCanvasBg(activeBgColor); } }}_document.onclick = function(){ bgGroup.classList.remove('active');}selectBg.onclick = function(e){ bgGroup.classList.add('active'); e.stopPropagation();} 7.实现改变画笔粗细的功能 实现思路: 实现让设置画笔的属性的对话框出现。 获取相应的元素节点。 当input=range的元素发生改变的时候,获取到的值赋值给lWidth。 然后设置context.lineWidth = lWidth。 let range1 = document.getElementById('range1');let lWidth = 2;let ifPop = false;range1.onchange = function(){ console.log(range1.value); console.log(typeof range1.value) thickness.style.transform = 'scale('+ (parseInt(range1.value)) +')'; console.log(thickness.style.transform ) lWidth = parseInt(range1.value*2);}// 画线函数function drawLine(x1,y1,x2,y2){ // ... context.lineWidth = lWidth; // ...}// 点击画笔brush.onclick = function(){ eraserEnabled = false; brush.classList.add('active'); eraser.classList.remove('active'); if(!ifPop){ // 弹出框 console.log('弹一弹') penDetail.classList.add('active'); }else{ penDetail.classList.remove('active'); } ifPop = !ifPop;} 8.实现改变画笔颜色的功能 实现思路跟 改变画板背景颜色 的思路类似。 let aColorBtn = document.getElementsByClassName("color-item");getColor();function getColor(){ for (let i = 0; i < aColorBtn.length; i++) { aColorBtn[i].onclick = function () { for (let i = 0; i < aColorBtn.length; i++) { aColorBtn[i].classList.remove("active"); this.classList.add("active"); activeColor = this.style.backgroundColor; ctx.fillStyle = activeColor; ctx.strokeStyle = activeColor; } } }} 9.实现改变撤销和重做的功能 实现思路: 保存快照:每完成一次绘制操作则保存一份 canvas 快照到 canvasHistory 数组(生成快照使用 canvas 的 toDataURL() 方法,生成的是 base64 的图片); 撤销和反撤销:把 canvasHistory 数组中对应索引的快照使用 canvas 的 drawImage() 方法重绘一遍; 绘制新图像:执行新的绘制操作时,删除当前位置之后的数组记录,然后添加新的快照。 let undo = document.getElementById("undo");let redo = document.getElementById("redo");// ...canvas.onmouseup = function(){ painting = false; canvasDraw();}let canvasHistory = [];let step = -1;// 绘制方法function canvasDraw(){ step++; if(step < canvasHistory.length){ canvasHistory.length = step; // 截断数组 } // 添加新的绘制到历史记录 canvasHistory.push(canvas.toDataURL());}// 撤销方法function canvasUndo(){ if(step >

0) {step--; / / ctx.clearRect; let canvasPic = new Image (); canvasPic.src = canvasHistory [step]; canvasPic.onload = function () {ctx.drawImage (canvasPic, 0Power0);} undo.classList.add ('active');} else {undo.classList.remove (' active') Alert ('can no longer undo');}} / / redo method function canvasRedo () {if (step < canvasHistory.length-1) {step++; let canvasPic = new Image (); canvasPic.src = canvasHistory [step]; canvasPic.onload = function () {/ / ctx.clearRect } redo.classList.add ('active');} else {redo.classList.remove (' active') alert ('already the latest record');}} undo.onclick = function () {canvasUndo ();} redo.onclick = function () {canvasRedo ();}

10. Compatible mobile terminal

The idea of realization is:

Determine whether the device supports touch

True, use the touch event; false, use the mouse event

/ /... if (document.body.ontouchstart! = = undefined) {/ / use touch event anvas.ontouchstart = function (e) {/ / start Touch} canvas.ontouchmove = function (e) {/ / start Slide} canvas.ontouchend = function () {/ / Slide end}} else {/ / use mouse event / /...} / /...

Step on the pit

Problem 1: if you change the browser window on the computer, the artboard will not be adaptive.

Solution:

In the onresize response event processing, the page size parameters obtained are the changed parameters.

When the window size changes, reset the width and height of the canvas, simply put, after the window changes, re-assign values to canvas.width and canvas.height.

/ / remember to execute the function autoSetSize, oh function autoSetSize () {canvasSetSize (); / / when executing this function, you will first set the width and height of canvas function canvasSetSize () {let pageWidth = document.documentElement.clientWidth; let pageHeight = document.documentElement.clientHeight; canvas.width = pageWidth; canvas.height = pageHeight } / / after the window size changes, the resize event will be triggered to reset the width and height of the canvas _ window.onresize = function () {canvasSetSize ();}}

Question 2: it's okay when the width of the drawing line is relatively small, but there will be problems once it is thicker.

Solution: take a look at the document and come up with the method by simply modifying the code that draws the lines

/ / the line drawing function function drawLine (x1magentin x2jiny2) {context.beginPath (); context.lineWidth = lWidth; / /-add-/ / set the end style of the line. Context.lineCap = "round"; / / set the style where the line meets the line indirectly context.lineJoin = "round"; / /-add-context.moveTo (x1Powery1); context.lineTo (x2memy2); context.stroke (); context.closePath ();}

Question 3: how to achieve round rubber sassafras?

Solution:

In canvas's API, it is the clearRect method that can clear pixels, but the clear area of the clearRect method is rectangular, after all, the eraser in most people's habits is round, so it introduces the powerful function of the clip region, that is, the clip method. The usage is simple:

Ctx.save () ctx.beginPath () ctx.arc (x2rect y2pi); ctx.clip () ctx.clearRect (0meme 0rect canvas.width.height); ctx.restore ()

The above code implements the erasure of the circular area, that is, first implement a circular path, then use the path as the clip area, and then clear the pixels. One thing to note is that you need to save the drawing environment first, and reset the drawing environment after clearing the pixels. If you don't reset it, future drawings will be limited to that clip area.

Question 4: how to be compatible with mobile?

1. Add meta tags

Because the browser initially zooms the page when it is now displayed on the mobile side, we can set the meta viewport attribute in the meta tag to tell the browser not to zoom the page, page width = user device screen width

/ * Page width = moving width: width=device-width users cannot scale: user-scalable=no scale: initial-scale=1 maximum scale: maximum-scale=1.0 minimum scale: minimum-scale=1.0*/

two。 Touch events are almost always used on the mobile side, unlike the PC side.

Because the mobile side is a touch event, the attribute touchstart/touchmove/touchend of H5 is used, but the PC side only supports mouse events, so feature detection is required.

In the touch event, coordinates are obtained through .touches [0] .clientX and .touches [0] .clientY, which is different from the mouse event.

Question 5: one problem is that after emptying, the painting is redrawn, and then the original painting appears.

Well, it's not a big problem, it's just that I missed to write context.beginPath (); I also spent a little time solving bug on it, which reminds me of "tens of thousands of lines of code, the first line of comments; non-standard programming, two lines of tears from colleagues", it's better to operate according to the document operation code, really fragrant!

Thank you for reading this article carefully. I hope the article "how to set up the drawing board through html5 through canvas" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report