简体   繁体   English

在HTML Canvas中绘制图像并将其另存为JPEG

[英]Drawing and saving an image as JPEG in HTML Canvas

I am creating an app which allows user to draw a digit(using mouse) in Canvas. 我正在创建一个应用程序,允许用户在Canvas中绘制数字(使用鼠标)。 When they click on submit, the image should be saved as a JPEG and Clear should Erase the digit drawn in canvas. 当他们单击提交时,图像应另存为JPEG,清除应擦除在画布中绘制的数字。 I am new to HTML5 Canvas. 我是HTML5 Canvas的新手。 I saw some tutorials which created a canvas, but I am unable to save and clear canvas. 我看到了一些创建画布的教程,但是无法保存和清除画布。 Any help would really be appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

Here is my HTML: 这是我的HTML:

<div style="padding-bottom: 20px;padding-left: 210px;">
<div class="btn-group" role="group" aria-label="...">
    <button type="button" id="save" class="btn btn-default">Submit</button>
    <button type="button" id="clear" class="btn btn-default">Clear</button>
</div></div>
</div>

Javascript within Script tag: Script标记内的Javascript:

var clear = document.getElementById('clear');
clear.addEventListener('click', clearCanvas);
var clearCanvas = function(e) {
   ctx.fillStyle = "white";
   ctx.fillRect(0, 0, 500, 400);
   ctx.clearRect(20, 20, 100, 50);
}

The tutorial you're using fails to mention a few key things: 您正在使用的教程没有提及一些关键事项:

  • The canvasInAPerfectWorld line isn't used: you can delete it. 未使用canvasInAPerfectWorld行:您可以删除它。
  • You need jQuery: just add <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script/> in your <head> section. 您需要jQuery:只需在您的服务器中添加<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script/> <head>部分。
  • You should wrap your javascript in the jQuery boilerplate, to ensure it gets executed after the rest to the document has loaded: $( document ).ready(function() { <your javascript here> }); 您应该将javascript包装在jQuery样板中,以确保在其余文档加载后执行它: $( document ).ready(function() { <your javascript here> });
  • The canvasWidth and canvasHeight variables are never set: add this line before the variables are used: var canvasWidth = 600; var cavasHeight = 400; 不会设置canvasWidthcanvasHeight变量:在使用变量之前添加以下行: var canvasWidth = 600; var cavasHeight = 400; var canvasWidth = 600; var cavasHeight = 400;
  • The variables mouseX and mouseY are never used: you can delete them (but take a look at the onClick() function two lines later to see what they would have been used for). 永远不要使用mouseX和mouseY变量:您可以删除它们(但请在两行之后查看onClick()函数,以了解它们的用途)。

The finished result should look like this: 完成的结果应如下所示:

<!DOCTYPE html>
<html>
<head>
<title>HTML5 Create HTML5 Canvas JavaScript Drawing App Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<style>canvas { border: 1px solid #ccc; }</style>
<script type="text/javascript">
$( document ).ready(function() {
var canvasWidth = 600; var cavasHeight = 400;

var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', cavasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
    canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");

$('#canvas').mousedown(function(e){
      paint = true;
      addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
      redraw();
    });

$('#canvas').mousemove(function(e){
      if(paint){
        addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
        redraw();
      }
    });

$('#canvas').mouseup(function(e){
      paint = false;
    });

$('#canvas').mouseleave(function(e){
      paint = false;
    });

$('#clear').click(function(){
  clickX.length = 0;
  clickY.length = 0;
  clickDrag.length = 0;
  redraw();
});

var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;

function addClick(x, y, dragging)
{
  clickX.push(x);
  clickY.push(y);
  clickDrag.push(dragging);
}

function redraw(){
      context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas

      context.strokeStyle = "#df4b26";
      context.lineJoin = "round";
      context.lineWidth = 5;

      for(var i=0; i < clickX.length; i++) {        
        context.beginPath();
        if(clickDrag[i] && i){
          context.moveTo(clickX[i-1], clickY[i-1]);
         }else{
           context.moveTo(clickX[i]-1, clickY[i]);
         }
         context.lineTo(clickX[i], clickY[i]);
         context.closePath();
         context.stroke();
      }
    }
    });
   </script>
   </head>
     <body>
       <div id="canvasDiv"></div>
    </body>
 </html>

As for saving your canvas as a JPEG, that's more complicated. 至于保存你的画布为JPEG,这是更为复杂。 As markE has pointed out, there's a related question here which shows one way to do it. 正如markE所指出的,这里有一个相关的问题显示了一种解决方法。


EDIT : Adding a 'Clear' button: 编辑 :添加一个“清除”按钮:

Your 'drawing' is really just a series of pen movements stored in the clickX, clickY and clickDrag arrays. 您的“绘图”实际上只是存储在clickX,clickY和clickDrag数组中的一系列笔移动。 Each time redraw() is called, the drawing gets recreated from the arrays. 每次调用redraw() ,都会从数组中重新创建图形。 So just drawing a white rectangle will only clear the screen until the next redraw() . 因此,仅绘制白色矩形只会清除屏幕,直到下一个redraw()为止。 Instead, you can clear the arrays by adding this to your javascript: 相反,您可以通过将其添加到javascript中来清除数组:

$('#clear').click(function(){
  clickX.length = 0;
  clickY.length = 0;
  clickDrag.length = 0;
  redraw();
});

(BTW by deleting the details of your original question, you make it hard for the next person to understand the context of the answers. You should either (a) add to your original question, or (b) ask a new question. Also you can upvote and/or accept any answers you find helpful. Thanks) (顺便说一句,通过删除原始问题的详细信息,您将很难让下一个人理解答案的上下文。您应该(a)添加到原始问题中,或者(b)提出新问题。可以投票和/或接受您认为有帮助的任何答案。(谢谢)

I think that's a duplicated question. 我认为这是一个重复的问题。 See here 看这里

Can I get image from canvas element and use it in img src tag? 我可以从canvas元素获取图像并在img src标签中使用它吗?

var image = new Image();
image.id = "pic"
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM