相关链接:
介绍
<canvas>
标签是图形容器,必须使用脚本来绘制图形
历史
https://www.w3school.com.cn/tags/tag_canvas.asp
最早 apple 提出,后其他浏览器(甚至包括ie)跟进
http://www.whatwg.org/specs/web-apps/current-work/
现成为html5的正式标签
支持版本(ie9)
标签是 HTML 5 中的新标签
<!-- 宽高像素必须在标签上指定,否则会被视为等比例缩放(如css) -->
<canvas height="400px" width="400px">不支持时显示</canvas>
画直线
var canvas = document.getElementById('canvasTest');
// 获取上下文对象
var c = canvas.getContext('2d');
c.beginPath(); // 开启一条路径
c.moveTo(100, 100); // 起点
c.lineTo(300, 300); // 终点
c.stroke(); // 上色
c.closePath(); // 关闭路径
demo: https://codepen.io/lawsssscat/pen/BarvZNZ
树状图
const canvas = document.getElementById('canvasTest');
const ctx = canvas.getContext('2d');
function drawLine(x1, y1, x2, y2, options={}) {
ctx.save(); // 保存样式
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = options.width;
ctx.strokeStyle = options.color;
ctx.stroke();
ctx.closePath();
ctx.restore(); // 复原样式
}
function drawRect(x, y, width, height, options={}) {
ctx.save(); // 保存样式
ctx.fillStyle = options.color;
ctx.fillRect(x, y, width, height);
ctx.restore(); // 复原样式
}
// 坐标轴
const axisOrigin = [100, 250];
const axisWidth = 300;
const axisHeight = 200;
const axisOptions = {
color: '#000',
width: 1
}
drawLine(axisOrigin[0], axisOrigin[1], axisOrigin[0], axisOrigin[1] - axisHeight, axisOptions);
drawLine(axisOrigin[0], axisOrigin[1], axisOrigin[0] + axisWidth, axisOrigin[1], axisOptions);
// 柱状图
const columnWidth = 20;
const columnGap = 20;
const columnData = (function() {
const result = [];
for(let i=0; i<7; i++) {
result.push({
height: Math.random()*200,
fillStyle: `rgb(${parseInt(Math.random()*256)},${parseInt(Math.random()*256)},${parseInt(Math.random()*256)})`
});
}
return result;
})();
// 树状图实现一:line
columnData.forEach((data, index) => {
const startX = axisOrigin[0] + (index + 1)*columnGap + (index)*columnGap + 0.5*columnWidth;
const startY = axisOrigin[1];
const endX = startX;
const endY = startY - data.height;
drawLine(startX, startY, endX, endY, {
color: data.fillStyle,
width: columnWidth
});
});
// 树状图实现2: Rect
columnData.reverse().forEach((data, index) => {
const x = axisOrigin[0] + (index + 1)*columnGap + (index)*columnGap;
const y = axisOrigin[1];
const width = columnWidth;
const height = 1 * data.height;
drawRect(x, y, width, height, {
color: data.fillStyle
});
});
demo: https://codepen.io/lawsssscat/pen/NWYegpy
画圆
const canvas = document.getElementById('canvasTest');
const ctx = canvas.getContext('2d');
let offset; // 不同高度
const pointOrigin = [100, 100];
const radius = 100;
const counterclockwise = true; // counterclockwise=逆时针
// 图形1:一笔过
offset = 0;
ctx.arc(pointOrigin[0], pointOrigin[1]+offset, radius, Math.PI*1, 0, !counterclockwise);
ctx.lineWidth = 3;
ctx.strokeStyle = '#f33';
ctx.stroke();
ctx.arc(pointOrigin[0]+2*radius, pointOrigin[1]+offset, radius, Math.PI*1, 0, counterclockwise);
ctx.stroke();
ctx.fillStyle = '#3f3';
ctx.fill();
demo: https://codepen.io/lawsssscat/pen/xxWmWRv
画文字
var canvas = document.getElementById('canvasTest');
const width=canvas.width, height=canvas.height;
// 获取上下文对象
var ctx = canvas.getContext('2d');
function drawPrepare(callback) {
ctx.save();
callback();
ctx.restore();
}
function drawLine(x1, y1, x2, y2, options={}) {
drawPrepare(() => {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
if(options.lineDashPattern) { // 虚线
ctx.setLineDash(options.lineDashPattern);
}
ctx.stroke();
ctx.closePath();
});
}
function drawRect(x, y, width, height, options={}) {
drawPrepare(() => {
if(options.fill!=false) {
ctx.fillStyle = options.fillStyle;
ctx.fillRect(x, y, width, height);
ctx.fill();
}
if(options.stroke==true) {
ctx.strokeStyle = options.strokeStyle;
ctx.lineWidth = options.lineWidth;
ctx.strokeRect(x, y, width, height);
ctx.stroke();
}
});
}
function drawText(text, x, y, options={}) {
drawPrepare(() => {
ctx.font = options.font || '400px 楷体';
ctx.textAlign = options.textAlign || 'center';
ctx.textBaseline = options.textBaseline || 'middle';
ctx.fillText(text, x, y);
});
}
// drawLine(0, 0, width, 0);
// drawLine(0, 0, 0, height);
// drawLine(0, height, width, height);
// drawLine(width, 0, width, height);
const optionsDefault = {
lineWidth: 1
}
drawRect(0, 0, width, height, {
fill: false,
stroke: true,
...optionsDefault
});
drawLine(0, height/2, width, height/2, {
...optionsDefault
});
drawLine(width/2, 0, width/2, height, {
...optionsDefault
});
const lineDashPattern = [20, 10];
drawLine(0, 0, width, height, {
...optionsDefault,
lineDashPattern
});
drawLine(width, 0, 0, height, {
...optionsDefault,
lineDashPattern
});
drawText('錢', width/2, height/2);
demo: https://codepen.io/lawsssscat/pen/GRxPVoQ
画图片(像素操作)
像素数据如下图:(四个数据为一组,分别为r,g,b,a)
var canvas = document.getElementById('canvasTest');
// 获取上下文对象
var ctx = canvas.getContext('2d');
const width=canvas.width, height=canvas.height;
function clear() {
ctx.clearRect(0, 0, width, height);
}
function drawPrepare(callback) {
ctx.save();
callback();
ctx.restore();
}
function drawRect(x, y, width, height, options={}) {
drawPrepare(() => {
ctx.beginPath();
ctx.strokeStyle = options.strokeStyle;
ctx.lineWidth = options.lineWidth;
ctx.strokeRect(x, y, width, height);
ctx.stroke();
ctx.closePath();
});
}
// config
const origin = [width/2, height/2];
const magnifyingScope = 200;
// img
const img = new Image();
// see https://stackoverflow.com/questions/26688168/uncaught-securityerror-failed-to-execute-getimagedata-on-canvasrenderingcont
img.crossOrigin = 'anonymous'; // crossOrigin attribute has to be set before setting src.If reversed, it wont work.
img.src = 'https://images.unsplash.com/photo-1660230855022-a24f71059183?crop=entropy&cs=tinysrgb&fm=jpg&ixid=MnwzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NjA5MTk0OTc&ixlib=rb-1.2.1&q=80';
// ================
function reset() {
clear();
ctx.drawImage(img, 0, 0, width, height);
}
function magnifying(x, y, _w, _h) {
// copy
const copy = ctx.getImageData(x, y, _w, _h);
ctx.putImageData(copy, width-_w, height-_h);
// border
drawRect(x, y, _w, _w);
drawRect(width-_w, height-_h, _w, _h);
}
img.onload = function() {
reset();
magnifying(origin[0]-magnifyingScope/2, origin[1]-magnifyingScope/2, magnifyingScope, magnifyingScope);
};
canvas.onmousemove = function(event) {
reset();
const canvasRect = canvas.getBoundingClientRect();
magnifying((event.clientX-canvasRect.x)-magnifyingScope/2, (event.clientY-canvasRect.y)-magnifyingScope/2, magnifyingScope, magnifyingScope);
}
demo: https://codepen.io/lawsssscat/pen/JjLxbpa
Demo
碰撞检测
var canvas = document.getElementById('canvasTest');
// 获取上下文对象
var ctx = canvas.getContext('2d');
const width=canvas.width, height=canvas.height;
function drawCircle(x, y, r, options={}) {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2);
ctx.fillStyle=options.color||'#111';
ctx.fill();
ctx.restore();
}
function clear() {
ctx.clearRect(0, 0, width, height);
}
function r(v) {
return Math.random()*v;
}
class Circular {
constructor() {
this.circular = {
speedX: (1+r(5))*(r(2)>1?1:-1),
speedY: 1+r(5)*(r(2)>1?1:-1),
x: r(width),
y: r(height),
radius: 10+r(10),
color: `rgb(${r(255)}, ${r(255)}, ${r(255)})`,
}
}
update() {
const circular = this.circular;
const x = circular.x = circular.x+circular.speedX;
if(x<=circular.radius || x>=width-circular.radius) {
circular.x = x<=circular.radius?circular.radius:width-circular.radius;
circular.speedX = -circular.speedX;
}
const y = circular.y = circular.y+circular.speedY;
if(y<=circular.radius || y>=height-circular.radius) {
circular.y = y<=circular.radius?circular.radius:height-circular.radius;
circular.speedY = -circular.speedY;
}
drawCircle(circular.x, circular.y, circular.radius, {
color: circular.color
});
}
}
const cNum = 10;
const cList = (function() {
const result = [];
for(let i=0; i<cNum; i++) {
result.push(new Circular());
}
return result;
})();
setInterval(function() {
clear();
cList.forEach(_c => _c.update());
}, 10);
demo: https://codepen.io/lawsssscat/pen/zYWyajL
碰撞检测 + 连线
const canvas = document.getElementById('canvasTest');
let width=canvas.width;
let height=canvas.height;
// 获取上下文对象
const ctx = canvas.getContext('2d');
function clear() {
ctx.clearRect(0, 0, width, height);
}
function r(v) {
return Math.random()*v;
}
function drawPrepare(callback) {
ctx.save();
callback();
ctx.restore();
}
function drawLine(x1, y1, x2, y2, options={}) {
drawPrepare(() => {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
if(options.lineDashPattern) { // 虚线
ctx.setLineDash(options.lineDashPattern);
}
ctx.stroke();
ctx.closePath();
});
}
function drawRect(x, y, width, height, options={}) {
drawPrepare(() => {
ctx.beginPath();
if(options.fill!=false) {
ctx.fillStyle = options.fillStyle;
ctx.fillRect(x, y, width, height);
ctx.fill();
}
if(options.stroke==true) {
ctx.strokeStyle = options.strokeStyle;
ctx.lineWidth = options.lineWidth;
ctx.strokeRect(x, y, width, height);
ctx.stroke();
}
ctx.closePath();
});
}
function drawText(text, x, y, options={}) {
drawPrepare(() => {
ctx.font = options.font || `${width/15}px 楷体`;
ctx.textAlign = options.textAlign || 'center';
ctx.textBaseline = options.textBaseline || 'middle';
if(options.fillTextCustom) {
options.fillTextCustom(ctx, ...arguments);
} else {
ctx.fillText(text, x, y);
}
});
}
function drawCircle(x, y, r, options={}) {
drawPrepare(() => {
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2);
ctx.fillStyle=options.color||'#111';
ctx.fill();
// ctx.stroke();
});
}
// ====================================================
const frame = 53; // frame/s
class Circular {
constructor() {
const speedBase = 100;
this.circular = {
speedX: (speedBase+r(speedBase))/frame*(r(2)>1?1:-1), // [speedBase, speedBase*2) px/s
speedY: (speedBase+r(speedBase))/frame*(r(2)>1?1:-1),
x: r(width),
y: r(height),
radius: 10+r(10),
color: `rgb(${r(255)}, ${r(255)}, ${r(255)})`,
}
}
update() {
const circular = this.circular;
const x = circular.x = circular.x+circular.speedX;
if(x<=circular.radius || x>=width-circular.radius) {
circular.x = x<=circular.radius?circular.radius:width-circular.radius;
circular.speedX = -circular.speedX;
}
const y = circular.y = circular.y+circular.speedY;
if(y<=circular.radius || y>=height-circular.radius) {
circular.y = y<=circular.radius?circular.radius:height-circular.radius;
circular.speedY = -circular.speedY;
}
drawCircle(circular.x, circular.y, circular.radius, {
color: circular.color,
});
}
}
class TextCircular extends Circular {
constructor(text) {
super();
this.circular.text = text;
}
update() {
super.update();
const circular = this.circular;
const textOptions = {
font: `${circular.radius*2}px`,
textAlign: 'start'
};
drawText(circular.text, circular.x+circular.radius*1.1, circular.y, {
...textOptions,
fillTextCustom: (_ctx, _text, _x, _y) => {
const _w = _ctx.measureText(_text).width;
if(_x+_w>=width) {
_x = circular.x-circular.radius*1.1;
_ctx.textAlign = 'end';
}
_ctx.fillText(_text, _x, _y);
}
});
}
}
// ====================================================
// drawLine(0, 0, width, 0);
// drawLine(0, 0, 0, height);
// drawLine(0, height, width, height);
// drawLine(width, 0, width, height);
function drawBorder() {
const optionsDefault = {
lineWidth: 1
}
drawRect(0, 0, width, height, {
fill: false,
stroke: true,
...optionsDefault
});
}
const languageArr = [
'JavaScript',
'Java',
'PHP',
'C',
'C++',
'C#',
'Python',
'Go',
'MySQL',
'Orical',
'Ruby',
'Shell',
'lua',
];
const circularNum = languageArr.length;
const circularArr = (function() {
const result = [];
for(let i=0; i<circularNum; i++) {
result.push(new TextCircular(languageArr[i]));
}
return result;
})();
setInterval(function() {
clear();
drawBorder();
circularArr.forEach(_c => _c.update());
for(let i=0; i<circularArr.length; i++) {
const sc = circularArr[i];
for(let j=i+1; j<circularArr.length; j++) {
const ec = circularArr[j];
drawLine(sc.circular.x, sc.circular.y, ec.circular.x, ec.circular.y);
}
}
drawText(`${width}x${height}`, 0, 0, {
textAlign: 'start',
textBaseline: 'top'
});
drawText(`frame:${frame}`, width, 0, {
textAlign: 'end',
textBaseline: 'top'
});
}, 1000/frame);
时钟
var canvas = document.getElementById('canvasTest');
const width=canvas.width, height=canvas.height;
// 获取上下文对象
var ctx = canvas.getContext('2d');
function clear() {
ctx.clearRect(0, 0, width, height);
}
function drawPrepare(callback) {
ctx.save();
callback();
ctx.restore();
}
function drawLine(x1, y1, x2, y2, options={}) {
drawPrepare(() => {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = options.lineWidth;
ctx.lineCap = options.lineCap;
ctx.strokeStyle = options.strokeStyle;
if(options.lineDashPattern) { // 虚线
ctx.setLineDash(options.lineDashPattern);
}
ctx.stroke();
ctx.closePath();
});
}
function drawRect(x, y, width, height, options={}) {
drawPrepare(() => {
if(options.fill!=false) {
ctx.fillStyle = options.fillStyle;
ctx.fillRect(x, y, width, height);
ctx.fill();
}
if(options.stroke==true) {
ctx.strokeStyle = options.strokeStyle;
ctx.lineWidth = options.lineWidth;
ctx.strokeRect(x, y, width, height);
ctx.stroke();
}
});
}
function drawText(text, x, y, options={}) {
drawPrepare(() => {
ctx.font = options.font || '100px 楷体';
ctx.textAlign = options.textAlign || 'center';
ctx.textBaseline = options.textBaseline || 'middle';
ctx.fillText(text, x, y);
});
}
function drawCircle(x, y, r, options={}) {
drawPrepare(() => {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2);
ctx.fillStyle=options.fillStyle||'#111';
ctx.fill();
ctx.restore();
});
}
// ======================================================
ctx.translate(width/2, height/2);
class Clock {
constructor() {
const context = this;
context.sizeText=30;
context.radiusBorder=180;
context.radiusSquare=165;
context.radiusSquare_width=1.5;
context.radiusSquare_sm=170;
context.radiusSquare_width_sm=1.25;
context.radiusText=140;
context.radiusSecond=140;
context.radiusSecond_width=2.5;
context.radiusMinute=120;
context.radiusMinute_width=5;
context.radiusHour=60;
context.radiusHour_width=10;
context.radiusPoint=10;
context.colorMain_bg='#fff';
context.colorMain_fg='#000';
context.colorMain_fg_lx='#ddd';
context.colorMain_fg_l='#aaa';
context.colorMain_red='#f00';
this.calc();
}
calc() {
const _d = new Date();
this.clock = {
hour: _d.getHours(),
min: _d.getMinutes(),
sec: _d.getSeconds()
}
}
draw() {
const context = this;
drawCircle(0, 0, context.radiusBorder, {
fillStyle: context.colorMain_bg
});
// number
for(let i=1; i<=12; i++) {
const offset = Math.PI/2;
const _r = context.radiusText;
const _p = Math.PI/6;
drawText(i, _r*Math.cos(_p*i-offset), _r*Math.sin(_p*i-offset), {
font: `${context.sizeText}px Arial`
});
}
// square
for(let i=1; i<=12*5; i++) {
const _r = context.radiusSquare_sm;
const _R = context.radiusBorder;
const _p = Math.PI/6/5;
drawLine(_R*Math.cos(_p*i), _R*Math.sin(_p*i), _r*Math.cos(_p*i), _r*Math.sin(_p*i), {
lineWidth: context.radiusSquare_width_sm,
strokeStyle: context.colorMain_fg_lx
});
}
for(let i=1; i<=12; i++) {
const _r = context.radiusSquare;
const _R = context.radiusBorder;
const _p = Math.PI/6;
drawLine(_R*Math.cos(_p*i), _R*Math.sin(_p*i), _r*Math.cos(_p*i), _r*Math.sin(_p*i), {
lineWidth: context.radiusSquare_width,
strokeStyle: context.colorMain_fg_l
});
}
// hour
(function() {
const _r = context.radiusHour;
const _p = Math.PI/6;
const _d = _p * (((context.clock.sec)/60+context.clock.min)/60+context.clock.hour-3);
drawLine(0, 0, _r*Math.cos(_d), _r*Math.sin(_d), {
lineWidth: context.radiusHour_width,
lineCap: 'round'
});
})();
// min
(function() {
const _r = context.radiusMinute;
const _p = Math.PI/(30);
const _d = _p * ((context.clock.sec)/60+context.clock.min-15);
drawLine(0, 0, _r*Math.cos(_d), _r*Math.sin(_d), {
lineWidth: context.radiusMinute_width,
lineCap: 'round'
});
})();
// sec
(function() {
const _r = context.radiusSecond;
const _p = Math.PI/(30);
const _d = _p * (context.clock.sec-15);
drawLine(0, 0, _r*Math.cos(_d), _r*Math.sin(_d), {
lineWidth: context.radiusSecond_width,
lineCap: 'round',
strokeStyle: context.colorMain_red
});
})();
drawCircle(0, 0, context.radiusPoint, {
fillStyle: context.colorMain_fg
});
}
}
const clock = new Clock();
setInterval(() => {
clock.calc();
console.log(clock.clock);
clock.draw();
}, 1000);
demo: https://codepen.io/lawsssscat/pen/abYXOzV
像素文字
demo: https://codepen.io/lawsssscat/pen/poLGaOP
var canvas = document.getElementById('canvasTest');
const width=canvas.width, height=canvas.height;
// 获取上下文对象
var ctx = canvas.getContext('2d');
function r(v) {
return Math.random()*v;
}
function clear() {
ctx.clearRect(0, 0, width, height);
}
function drawPrepare(callback) {
ctx.save();
callback();
ctx.restore();
}
function drawLine(x1, y1, x2, y2, options={}) {
drawPrepare(() => {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.lineWidth = options.lineWidth;
ctx.strokeStyle = options.strokeStyle;
if(options.lineDashPattern) { // 虚线
ctx.setLineDash(options.lineDashPattern);
}
ctx.stroke();
ctx.closePath();
});
}
function drawRect(x, y, width, height, options={}) {
drawPrepare(() => {
if(options.fill!=false) {
ctx.fillStyle = options.fillStyle;
ctx.fillRect(x, y, width, height);
ctx.fill();
}
if(options.stroke==true) {
ctx.strokeStyle = options.strokeStyle;
ctx.lineWidth = options.lineWidth;
ctx.strokeRect(x, y, width, height);
ctx.stroke();
}
});
}
function drawText(text, x, y, options={}) {
drawPrepare(() => {
ctx.font = options.font || '400px 楷体';
ctx.textAlign = options.textAlign || 'center';
ctx.textBaseline = options.textBaseline || 'middle';
ctx.fillText(text, x, y);
});
}
function drawCircle(x, y, r, options={}) {
drawPrepare(() => {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2);
ctx.fillStyle=options.fillStyle||'#111';
ctx.fill();
ctx.restore();
});
}
// ================================================================================
const frame = 53; // 刷新帧 f/s
const leap = 4; // 像素间隔
const fontSize = 36;
const fontFamily = 'arial';
const transitionDuration = 3000; // ms
// 字
drawText('♥', width/2, height/2);
// 获取像素
const pixelArr = ctx.getImageData(0, 0, width, height);
clear();
// 筛选有效像素
const pointArr = [];
for(let x=0; x<width; x+=leap) {
for(let y=0; y<height; y+=leap) {
const _index = (x+y*width)*4;
const _pixel = pixelArr.data.slice(_index, _index+4);
if(_pixel[3]>128) {
// drawCircle(x,y,1, {
// fillStyle: '#f00'
// });
pointArr.push({
targetX: x,
targetY: y,
x: r(width),
y: r(height)
});
}
}
}
// run
const _moveTimes = parseInt(transitionDuration/frame)+1;
let _t=0;
setInterval(() => {
const _divide = _moveTimes - _t;
if(_divide>0) {
_t++;
clear();
// font
pointArr.forEach(point => {
const _dx = point.targetX - point.x;
const _dy = point.targetY - point.y;
const _x = point.x + _dx/_divide;
const _y = point.y + _dy/_divide;
drawCircle(_x, _y, 1);
point.x = _x;
point.y = _y;
});
// config
drawText(`frame:${frame}`, width, 0, {
textAlign: 'end',
textBaseline: 'top',
font: `${fontSize}px ${fontFamily}`
});
drawText(`${width}x${height}`, 0, 0, {
textAlign: 'start',
textBaseline: 'top',
font: `${fontSize}px ${fontFamily}`
});
drawText(`times:${_divide}/${_moveTimes}(${transitionDuration}ms)`, 0, height, {
textAlign: 'start',
textBaseline: 'bottom',
font: `${fontSize}px ${fontFamily}`
});
}
}, 1000/frame);