<!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>