1. 绘制多边形
在画布中以鼠标按下的点为圆心,以鼠标划过的距离为半径绘制多边形:
var Polygon = function(){
this.mouseIn = false
this.startPoints = {} //鼠标在画布中按下的点左边
this.line_list = {}
this.imageData = null
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
canvas.onmousedown = (event) => {
this.saveImage(ctx, canvas)
let some = this.pointsOnCanvas(event, canvas)
this.startPoints.x = some.x;
this.startPoints.y = some.y
this.mouseIn = true
}
canvas.onmousemove = (event) => {
if(this.mouseIn){ //如果按下鼠标并拖行
this.loadingImage(ctx)
this.line_list = this.pointsOnCanvas(event, canvas)
ctx.beginPath()
let radius = this.getRadius()
let startAngel = 0 //开始角度
let sides = 8 //边数
let startX = this.mousedown.x + radius * Math.cos(Math.PI*startAngel/180) //这里其实是角度转为弧度的算法:2*Math.PI/360 * startAngel(2π弧度=360度,所以1度=2π/360)
let startY = this.mousedown.y + radius * Math.sin(Math.PI*startAngel/180)
ctx.moveTo(startX, startY)
for(let i=1;i<sides;i++){
let nextX = this.mousedown.x + radius * Math.cos(Math.PI/180 * (i*360/sides)+startAngel)
let nextY = this.mousedown.y + radius * Math.sin(Math.PI/180 * (i*360/sides)+startAngel)
ctx.lineTo(nextX, nextY);
}
ctx.closePath();
ctx.lineWidth = 2;
ctx.stroke();
}
}
canvas.onmouseup = () => {
this.mouseIn = false //鼠标抬起来了
}
//算出你点击在canvas画布的坐标 并返回
Polygon.prototype.pointsOnCanvas = function(event, canvas){
var rect = canvas.getBoundingClientRect()
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
}
}
// 获取半径
Polygon.prototype.getRadius = function(){
var x_width = Math.abs(line_list.x - this.mousedown.x)
var y_width = Math.abs(line_list.y - this.mousedown.y)
return Math.sqrt(x_width*x_width + y_width*y_width)
}
Polygon.prototype.saveImage = function(ctx, canvas){ //储存此刻画布数据
this.imageData = ctx.getImageData(0,0,canvas.width,canvas.height)
}
Polygon.prototype.loadingImage = function(ctx){ //导入画布数据
ctx.putImageData(this.imageData,0,0)
}
}
效果如下:
2. 实现图片反转,显示为底片效果
<input type="file" onChange="chooseFile" />
<img :src="src"> //正常图片
<img :src="revertSrc"> //反转后的图片
function chooseFile(e){
let imgFile = e.target.files[0]
let reader = new FileReader()
let img = new Image()
reader.onload = () => {
src = reader.result
img.src = reader.result
}
img.onload = () => {
revertSrc = createRevertPic(img)
}
reader.readAsDataURL(imgFile)
}
//图片反转
function createRevertPic(img){
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
var c = ctx.getImageData(0, 0, img.width, img.height);
for(var i = 0; i < c.height; ++i){
for(var j = 0; j < c.width; ++j){
var x = i*4*c.width + 4*j, //imagedata读取的像素数据存储在data属性里,是从上到下,从左到右的,每个像素需要占用4位数据,分别是r,g,b,alpha透明通道
r = c.data[x],
g = c.data[x+1],
b = c.data[x+2];
c.data[x+3] = 150; //透明度设置为150,0表示完全透明
//图片反相:
c.data[x] = 255-r;
c.data[x+1] = 255-g;
c.data[x+2] = 255-b;
}
}
ctx.putImageData(c,0,0);
return canvas.toDataURL(); //返回canvas图片数据为base64的url
}
效果如下: