Javascript HTML5 Canvas实现的一个画板

前端之家收集整理的这篇文章主要介绍了Javascript HTML5 Canvas实现的一个画板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本文实例为大家分享了HTML5 Canvas实现的一个画板代码,供大家参考,具体内容如下

<Meta charset="utf-8"> DEMO6:<a href="https://www.jb51.cc/tag/zidingyi/" target="_blank" class="keywords">自定义</a>画板 不支持canvas

<button style="width: 80px;background-color: white;" onclick="linw=4;">4PX
<button style="width: 80px;background-color: white;" onclick="linw=8;">8PX
<button style="width: 80px;background-color: white;" onclick="linw=16;">16PX

<button style="width: 80px;background-color: white;" onclick="copyimage();">EXPORT



<img src="" id="image_png" width="600px" height="300px">

<script type="text/javascript">
var canvas = document.getElementById('canvas'); //获取标签
var ctx = canvas.getContext("2d");

var fillStyle = "black";
ctx.fillRect(0,600,300);
var onoff = false; //按下标记
var oldx = -10;
var oldy = -10;
//设置颜色
var linecolor = "white";
var linw = 4;
canvas.addEventListener("mousemove",draw,true); //鼠标移动事件
canvas.addEventListener("mousedown",down,false); //鼠标按下事件
canvas.addEventListener("mouseup",up,false); //鼠标弹起事件
function down(event){
onoff = true;
oldx = event.pageX - 10;
oldy = event.pageY - 10;
}
function up(){
onoff = false;
}
function draw(event){
if (onoff==true) {
var newx = event.pageX - 10;
var newy = event.pageY - 10
ctx.beginPath();
ctx.moveTo(oldx,oldy);
ctx.lineTo(newx,newy);
ctx.strokeStyle = linecolor;
ctx.lineWidth = linw;
ctx.lineCap = "round";
ctx.stroke();

  oldx = newx;
  oldy = newy;
}

}
function copyimage(event)
{
var img_png_src = canvas.toDataURL("image/png"); //将画板保存为图片格式的函数
document.getElementById("image_png").src = img_png_src;
}

以上就是本文的全部内容,希望对大家的学习有所帮助。

原文链接:https://www.f2er.com/js/49050.html

猜你在找的JavaScript相关文章