如何在HTML 5画布上用鼠标绘制
在这篇文章中,我们将探讨一些用鼠标指针在HTML 5画布上绘制的方法。HTML画布实质上是各种图形元素(如正方形、矩形、弧线、图像等)的容器。它为我们提供了对画布内部图形元素进行动画控制的灵活能力。然而,向画布添加功能必须通过JavaScript来完成。
- beginPath() : 每次鼠标左键被点击时,开始一个新的路径。
- lineWidth : 设置将绘制的线的宽度。
- strokeStyle : 在这方面,我们将其用于将线的颜色设置为黑色。可以更改此属性以产生不同颜色的线。
- moveTo() : 将路径的起始位置移动到画布上的指定坐标。
- lineTo() : 从起始位置创建一条线到指定的坐标。
- stroke() : 对创建的线进行描边。如果没有这个方法,线将不可见。
示例: 创建一个Canvas元素并添加JavaScript功能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
Draw with the mouse in a HTML5 canvas
</title>
<style>
* {
overflow: hidden;
}
body {
text-align: center;
}
h1 {
color: green;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<b>Draw anything you want</b>
<hr>
<canvas id="canvas"></canvas>
<script src="index.js"></script>
</body>
</html>
JavaScript代码
// wait for the content of the window element
// to load, then performs the operations.
// This is considered best practice.
window.addEventListener('load', ()=>{
resize(); // Resizes the canvas once the window loads
document.addEventListener('mousedown', startPainting);
document.addEventListener('mouseup', stopPainting);
document.addEventListener('mousemove', sketch);
window.addEventListener('resize', resize);
});
const canvas = document.querySelector('#canvas');
// Context for the canvas for 2 dimensional operations
const ctx = canvas.getContext('2d');
// Resizes the canvas to the available size of the window.
function resize(){
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
// Stores the initial position of the cursor
let coord = {x:0 , y:0};
// This is the flag that we are going to use to
// trigger drawing
let paint = false;
// Updates the coordianates of the cursor when
// an event e is triggered to the coordinates where
// the said event is triggered.
function getPosition(event){
coord.x = event.clientX - canvas.offsetLeft;
coord.y = event.clientY - canvas.offsetTop;
}
// The following functions toggle the flag to start
// and stop drawing
function startPainting(event){
paint = true;
getPosition(event);
}
function stopPainting(){
paint = false;
}
function sketch(event){
if (!paint) return;
ctx.beginPath();
ctx.lineWidth = 5;
// Sets the end of the lines drawn
// to a round shape.
ctx.lineCap = 'round';
ctx.strokeStyle = 'green';
// The cursor to start drawing
// moves to this coordinate
ctx.moveTo(coord.x, coord.y);
// The position of the cursor
// gets updated as we move the
// mouse around.
getPosition(event);
// A line is traced from start
// coordinate to this coordinate
ctx.lineTo(coord.x , coord.y);
// Draws the line.
ctx.stroke();
}
输出: 当 flag 的值为 true 时,函数 sketch() 将被执行。在 beginPath() 之后更新存储在 coord 对象中的坐标很重要,因此调用 getPosition(event) 函数。在将 JavaScript 文件链接到 HTML 文件后,将得到以下代码。