canvas处理压缩照片并回显:https://cengjingdeshuige.oss-cn-beijing.aliyuncs.com/20180512/cannovs%E5%AD%A6%E4%B9%A0.html

<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>画布标签,转换照片宽度,等比压缩</title>
</head> <body>
<canvas id="myCanvas" width="800" height="800" style="border:1px solid #000000;">
</canvas> <p>图片转换</p>
<p>原图:</p>
<img id="scream" src="https://cengjingdeshuige.oss-cn-beijing.aliyuncs.com/20180512/3.jpg" alt="The Scream" width="220" height="277">
<p>Canvas等比转换过的:</p>
<canvas id="myCanvas_img" style="border:1px solid red;"></canvas>
<p>转换后输出的图片Base64</p>
<img src="" id="base64" alt="base64">
<script>
var cannovsBox = document.getElementById('myCanvas_img')
var img = document.getElementById('scream')
img.onload = function () {
var imgsInit = new Image()
imgsInit.src = img.src
var ww = imgsInit.width
var hh = imgsInit.height
console.log(ww)
console.log(hh)
var width = ww
var height = hh
if (width > 400) {
width = 400
height = width * hh / ww
}
console.log(width, height)
cannovsBox.setAttribute("width", width);
cannovsBox.setAttribute("height", height); var huabi = cannovsBox.getContext('2d')
var sx = 0 // 开始剪切的x坐标
var sy = 0 // 开始剪切的y坐标
var swidth = ww
var sheight = hh
var x = 0
var y = 0
huabi.drawImage(img,sx,sy,swidth,sheight,x,y,width,height);
console.log(cannovsBox)
// 图片转换成base64位, 必须在服务器同源策略下,服务器允许跨域,不然会报错
var url = cannovsBox.toDataURL()
console.log(url)
document.getElementById('base64').src = url }
</script>
<script>
// 画图的部分,上边是照片处理的
var c = document.getElementById('myCanvas')
var ctx = c.getContext('2d') // 创建对象
// 画长方形
// ctx.fillStyle = 'red' // 画笔颜色
// ctx.fillRect(10, 5, 150, 75) // 画点
// 画线段,开始坐标到结束坐标
ctx.moveTo(10, 10) // 开始的坐标
ctx.lineTo(200, 10) // 结束的坐标
ctx.stroke() // 绘制
ctx.moveTo(200, 10)
ctx.lineTo(200, 200)
ctx.stroke()
ctx.moveTo(200, 200)
ctx.lineTo(10, 10)
ctx.stroke() // 画箭头
ctx.moveTo(300, 300) // 箭头上线
ctx.lineTo(500, 300)
ctx.stroke()
ctx.moveTo(300, 310) // 箭头下线
ctx.lineTo(500, 310)
ctx.stroke()
ctx.moveTo(490, 280) // 上斜线
ctx.lineTo(510, 305)
ctx.stroke()
ctx.moveTo(510, 305) // 下斜线
ctx.lineTo(490, 320)
ctx.stroke() // 画圆蛋
ctx.beginPath()
ctx.arc(100, 500, 50, 0, 2 * Math.PI) // arc(x,y,r,start:起点,stop:结束的位置)
ctx.stroke()
// 半圆蛋
ctx.beginPath()
ctx.arc(300, 500, 50, Math.PI, 2 * Math.PI)
ctx.stroke()
// 给半圆 封口
ctx.moveTo(250, 500)
ctx.lineTo(350, 500)
ctx.stroke() // 创建渐变
var grd = ctx.createLinearGradient(510, 510, 700, 520); // 创建渐变 (x,y,x1,y1) 都是以父元素0点为起点
// x0渐变开始点的 x 坐标 y0渐变开始点的 y 坐标 x1 渐变结束点的 x 坐标 y1 渐变结束点的 y 坐标
grd.addColorStop(0, 'red')
grd.addColorStop(0.5, 'blue')
grd.addColorStop(1, 'green')
// 填充渐变
ctx.fillStyle = grd
ctx.fillRect(510, 510, 150, 80) // (x,y,w,h) x,y的位置,宽高 都是以父元素的0点为起点
</script>
</body> </html>
上一篇:Linux之安装常用软件


下一篇:使用virsh搭建虚拟机管理环境