300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > html页面涂鸦 HTML5 | Canvas画笔小应用(涂鸦板)

html页面涂鸦 HTML5 | Canvas画笔小应用(涂鸦板)

时间:2021-11-03 05:50:41

相关推荐

html页面涂鸦 HTML5 | Canvas画笔小应用(涂鸦板)

JavaScript

语言:

JaveScriptBabelCoffeeScript

确定

const canvas = document.querySelector('#draw');

const ctx = canvas.getContext('2d');

canvas.width = window.innerWidth;

canvas.height = window.innerHeight;

ctx.strokeStyle = '#BADA55'; //ctx is the canvas

ctx.lineJoin = 'round';

ctx.lineCap = 'round';

ctx.lineWidth = 100;

// ctx.globalCompositeOperation = 'multiply';

let isDrawing = false;

let lastX = 0;

let lastY = 0;

let hue = 0;

let direction = true;

function draw(e) {

if (!isDrawing) return; // stop the fn from running when they are not moused down

console.log(e);

ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;

ctx.beginPath();

// start from

ctx.moveTo(lastX, lastY);

// go to

ctx.lineTo(e.offsetX, e.offsetY);

ctx.stroke();

[lastX, lastY] = [e.offsetX, e.offsetY];

hue++;

if (hue >= 360) {

hue = 0;

}

if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {

direction = !direction;

}

if (direction) {

ctx.lineWidth++;

} else {

ctx.lineWidth--;

}

}

canvas.addEventListener('mousedown', (e) => {

isDrawing = true;

[lastX, lastY] = [e.offsetX, e.offsetY];

});

canvas.addEventListener('mousemove', draw);

canvas.addEventListener('mouseup', () => isDrawing = false);

canvas.addEventListener('mouseout', () => isDrawing = false);

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。