本文共 2272 字,大约阅读时间需要 7 分钟。
在开始绘图之前,首先需要设置Canvas的宽高。可以通过设置width
和height
属性来指定绘制区域的大小,或者通过JavaScript动态设置以跟随窗口大小变化。对于不支持Canvas的浏览器,可以添加友好的提示信息。
let canvas = document.querySelector('#mycanvas');canvas.width = window.innerWidth;canvas.height = window.innerHeight;window.addEventListener('resize', function () { canvas.width = window.innerWidth; canvas.height = window.innerHeight;});if (!canvas.getContext) return;let ctx = canvas.getContext('2d');// 获取像素数据let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);// 获取图像数据URLlet imgURL = canvas.toDataURL('image/png');
Canvas支持多种绘制元素,包括直线、矩形、圆、贝塞尔曲线、图片、文本等。以下是常用元素的绘制方法示例。
ctx.strokeStyle = 'green';ctx.lineWidth = '10';ctx.lineJoin = 'round';ctx.lineCap = 'round';ctx.beginPath();ctx.moveTo(50, 50);ctx.lineTo(100, 100);ctx.stroke();
ctx.strokeStyle = 'black';ctx.lineWidth = '2';ctx.strokeRect(10, 10, 200, 100);
ctx.beginPath();ctx.arc(300, 300, 50, 0, Math.PI * 2);ctx.stroke();
ctx.beginPath();ctx.bezierCurveTo( 50, 50, 200, 150, 150, 300);ctx.stroke();
let img = new Image();img.src = './image/0.jpg';img.onload = function () { let pattern = ctx.createPattern(img, 'repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 200, 200); ctx.drawImage(img, 0, 300, 100, 100);};
ctx.fillStyle = 'black';ctx.font = '20px Arial';ctx.textAlign = 'center';ctx.textBaseline = 'middle';ctx.fillText('欢迎访问我们的网站', canvas.width/2, canvas.height/2);
Canvas支持线性渐变和径向渐变,可以通过createLinearGradient
和createRadialGradient
创建,并将其应用于填充或描边。
let gra = ctx.createLinearGradient(800, 10, 1000, 10);gra.addColorStop(0, 'red');gra.addColorStop(1, 'blue');ctx.fillStyle = gra;ctx.fillRect(800, 0, 200, 400);
let gra = ctx.createRadialGradient(900, 50, 50, 900, 50, 100);gra.addColorStop(0, 'red');gra.addColorStop(0.5, 'green');gra.addColorStop(1, 'blue');ctx.fillStyle = gra;ctx.fillRect(800, 0, 300, 400);
globalCompositeOperation
属性用于控制新绘制内容与旧内容的混合方式。常用的值包括'source-over'
、'destination-over'
等。
ctx.globalCompositeOperation = 'lighter';ctx.fillStyle = 'red';ctx.fillRect(50, 50, 100, 100);ctx.fillStyle = 'green';ctx.fillRect(100, 100, 100, 100);
通过设置不同的globalCompositeOperation
值,可以实现不同的混合效果,如'lighter'
会显示两种颜色的重叠部分混合后的效果。
转载地址:http://jmctz.baihongyu.com/