canvas使用基础方法
canvas使用基础方法
canvas简介
HTML5 <canvas> 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成。<canvas> 标签只是图形容器,必须使用脚本来绘制图形。可以通过多种方法使用 canvas 绘制路径,盒、圆、字符以及添加图像。
canvas的基本用法
创建canvas画布:
<canvas id="myCanvas" width="400" height="300">您的浏览器不支持</canvas>
var myCanvas = document.getElementById('myCanvas'); var ctx = myCanvas.getContext('2d');
ctx.beginPath();//开始绘制 ctx.fill(); //填充
绘制正方形 ctx.rect(x,y,width,height)

ctx.beginPath();//开始绘制 ctx.rect(40,40,100,100); ctx.fillStyle = 'lightblue'; ctx.fill(); //填充
//绘制边框
ctx.strokeStyle = 'lightcoral';
ctx.stroke();
绘制三角形 ctx.moveTo(x,y) 绘笔移动到(x,y)点
ctx.lineTo(x,y)画线到(x,y)点

//手绘三角形 ctx.beginPath(); ctx.moveTo(200,50); ctx.lineTo(250,100); ctx.lineTo(150,100); // ctx.lineTo(200,50); ctx.closePath();//解决因边框线太粗而导致的边框线无法闭合起来 ctx.fillStyle = 'lightblue'; ctx.fill(); ctx.lineWidth = 10;
ctx.strokeStyle = 'lightcoral'; ctx.stroke();
绘制圆形 ctx.arc(x,y,r,起始角,结束角)

ctx.beginPath(); ctx.arc(50,200,40,0,2*Math.PI); ctx.fill();
绘制半圆

//下半圆
ctx.beginPath(); ctx.arc(150,200,40,0,Math.PI); ctx.fill(); //上半圆 ctx.beginPath(); ctx.arc(230,200,40,0,Math.PI,true); ctx.fill();
绘制文字 ctx.fillText(text,x,y,maxWidth)

ctx.beginPath(); ctx.font='26px 微软雅黑'; ctx.fillText('你好',50,280); ctx.lineWidth = 0.5; ctx.strokeText('你好',50,280);
图片绘制 ctx.shadowColor 阴影颜色
ctx.shadowOffsetX 属性设置或返回阴影与形状的水平距离
ctx.shadowOffsetX 属性设置或返回阴影与形状的垂直距离
ctx.shadowBlur 阴影模糊度

// 图片绘制 var img = new Image(); img.src='img/logo.png'; window.onload = function(){ ctx.beginPath();ctx.drawImage(img,20,20,100,100) } ctx.shadowColor = 'lightseagreen' ctx.shadowOffsetX = 4; ctx.shadowOffsetY = 4; ctx.shadowBlur = 14;

浙公网安备 33010602011771号