How to Upload Image into HTML5 Canvas

How to upload image into HTML5 canvas

I assume you mean, to load an image into the canvas and not uploading the image from the canvas.

It'd probably be a good idea to read through all the canvas articles they have over here
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images

But basically what you want to do is create an image in javascript, and set the image.src = to whatever the file location is. In the case of loading images from the user on their end, you're going to want to use the File System API.

Threw together a brief example here: http://jsfiddle.net/influenztial/qy7h5/

function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}

javascript: upload image file and draw it into a canvas

const EL = (sel) => document.querySelector(sel);const ctx = EL("#canvas").getContext("2d");
function readImage() { if (!this.files || !this.files[0]) return; const FR = new FileReader(); FR.addEventListener("load", (evt) => { const img = new Image(); img.addEventListener("load", () => { ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.drawImage(img, 0, 0); }); img.src = evt.target.result; }); FR.readAsDataURL(this.files[0]);}
EL("#fileUpload").addEventListener("change", readImage);
canvas {display: block;}
<input type='file' id="fileUpload" /><canvas id="canvas" width="300" height="200"></canvas>

How to save an HTML5 Canvas as an image on a server?

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

<canvas id="myCanvas" width="578" height="200"></canvas>

<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

// begin custom shape
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);

// complete custom shape
context.closePath();
context.lineWidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = 'blue';
context.stroke();
</script>

Upload image onto canvas

The same general approach should work. However, your new library expects an <img> DOM element when adding a layer.

The following does what you want:

http://codepen.io/nonplus/full/fjzcv/

  $("#uploader").change(function(e) {
var reader = new FileReader();
var title = e.target.value.replace(/.*[\\/]|(\.[^\.]+$)/g, "");
reader.onload = function(event){
var $img = $("<img/>").attr("src", event.target.result);
jCollage.addLayer($img.get(0)).setTitle(title);
updateLayers(jCollage.getLayers());
$("#layer_" + (jCollage.getLayers().length - 1)).addClass("selected");
}
reader.readAsDataURL(e.target.files[0]);
});

Upload Image to Existing HTML5 Canvas

Here is the KineticJS code that draws the student’s name and photo on your id-card.

The student can drag their name and photo around the card.

The photo is not resizeable, but I have scaled the photo to fit in the photo area of your card. If you change the card layout, you can easily adjust the width/height in the KineticJS Image Object.

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/9jTtb/

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://www.html5canvastutorials.com/libraries/kinetic-v4.3.0-beta2.js"></script>
<style>
#container{
border:solid 1px #ccc;
margin-top: 10px;
}
</style>
<script>
$(function(){

var stage = new Kinetic.Stage({
container: 'container',
width: 472,
height: 286
});

var layer=new Kinetic.Layer();
stage.add(layer);

var preload=[];
var images=[];
preload.push("http://dl.dropbox.com/u/139992952/idcard.png");
// I use a demo photo here
// Of course in your live site, you would use URL.createObjectURL
preload.push("http://macmcrae.com/wp-content/uploads/2009/07/bubblebobble.jpg");
preloadImages(preload,init);

function init(images){
KImage("background",0,0,472,286,false,layer,images[0]);
KImage("Photo",284,105,160,160,true,layer,images[1]);
KText("Name",50,190,"Verdana",27,"black",true,layer,"Sam Student");
}

// image preloader
function preloadImages(sources,callback){
var images=[];
var count=0;
for(var i=0;i<preload.length;i++){
images[i]=new Image();
images[i].onload=function(){
if(++count==preload.length){
callback(images);
}
}
images[i].src=preload[i];
}
}

// build the specified KineticJS Image and add it to the stage
function KImage(id,x,y,width,height,isDraggable,layer,img){
var kImg=new Kinetic.Image({
image:img,
id:id,
x:x,
y:y,
width:width,
height:height,
draggable:isDraggable
});
layer.add(kImg);
stage.draw();
}

// build the specified KineticJS Text and add it to the stage
function KText(id,x,y,font,fontsize,color,isDraggable,layer,text){
var kText=new Kinetic.Text({
text:text,
id:id,
x:x,
y:y,
fontFamily:font,
fontSize:fontsize,
fill:color,
draggable:isDraggable
});
layer.add(kText);
stage.draw();
};

}); // end $(function(){});

</script>
</head>

<body>
<div id="container"></div>
<img id="test"/>
</body>
</html>

[Edited to answer OP’s additional requests]

I looked at your code but couldn’t find any php upload script, so here is the general idea.

I assume you’ve already set up your configuration in php.ini, especially these:

  • file_uploads = true;
  • upload_max_filesize=2M; // or whatever max size you want the user to upload
  • post_max_size=8M;

I assume you’ve already created a file folder to hold your uploaded files and given the webserver ownership (or adequate permissions). The code below assumes the subdirectory is “uploads”.

Then the PHP code below will upload your user’s image and store it in the “uploads” directory using the same name as the user’s original file.

You still must modify this code for any bounds/error checking you feel is necessary. Personally, I would do these as a minimum:

  • $_FILES is not empty and it is an array
  • $_FILES reports no errors occurred
  • File name contains only these English characters [0-9][A-Z][.]
  • File name is not more than250 characters
  • File is not empty
  • File is not larger than upload_max_size
  • File has one of these extensions: .jpg, .jpeg, .gif, .png // or whatever you accept
  • File does not already exist // add logic to overwrite or bail out
  • Catch routines on failures of the above tests

The php part would look like this:

<?php

var $uploadDirectory="uploads/"; // or whatever dir you set up
var $maxFileSize=1000000; // or whatever max-size you allowed

// assuming 'file' is the name of your input-type-file tag

// oops, got an error
if ($_FILES["file"]["error"] > 0){echo "Error occured: " . $_FILES["file"]["error"] . "<br>"; }

// get filepaths
var $tempfile=$_FILES["file"]["tmp_name"];
var $basefile=basename($_FILES['file']['name']);

// save the user's file
move_uploaded_file( $tempfile, $uploadDirectory . $basefile );

// do whatever other postback stuff you need to do

?>

And the HTML form would be something like this:

<form action="upload.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<input type="file" name="file"/>
<input type="submit" name="submit" value="upload" />
</form>

HTML5: Drawing and upload image directly

I would add an invisible form, and a button which triggers a click event on the invisible file input when it's clicked.

Your HTML

<canvas id="c" width="400" height="280"></canvas>
<a id="download-canvas" href="#">Download</a>
<!-- You may add an invisible file input -->
<form action="/url" method="post">
<input type="file" style="display:none">
<button id="upload">Select file</button>
<button type="submit">Send</button>
</form>

Your JS

(function() {
var canvas = document.getElementById('c'),
cxt = canvas.getContext('2d'),
downloadLink = document.getElementById('download-canvas');

cxt.fillStyle = 'red';
cxt.fillRect(100, 50, 200, 200);
cxt.clearRect(150, 100, 100, 100);

downloadLink.href = canvas.toDataURL();
downloadLink.download = "download.png";
var button = document.getElementById('upload');
button.addEventListener("click", showForm);

})();

function showForm(){
$("#upload").click();
}

Add image to HTML5 canvas on file upload issue

first the result, here : http://codepen.io/anon/pen/qBmnC/

Your shape object can only draw one single hard-coded image, so change this and have shape be either a color or an image. In fact for this you just have to change shape.draw since the 'type' of the fill does not matter in the constructor.
So just test the fill and draw accordingly :

// Tekent de Shape
Shape.prototype.draw = function(ctx) {
var locx = this.x;
var locy = this.y;
var fill = this.fill ;
if (typeof fill == 'string' )
{
ctx.fillStyle = fill;
ctx.fillRect(locx, locy, this.w, this.h);
}
else
{
ctx.drawImage(fill, locx, locy, this.w, this.h);
}
}

then on image load i just add a shape that has this image as fill :

function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var imgNew = new Image();
imgNew.onload = function(){
s.addShape(new Shape(60,60,imgNew.width,imgNew.height,imgNew));
}
imgNew.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}

I had to put the shape collection, s, as a global var.
You can also see that i used the same scheme in init() to
add an image once it's loaded.



Related Topics



Leave a reply



Submit