-1

I would like to take part of an image and make it into a new image in java script, so something like:

var image2 = new Image(); image2.src = image1.src(10,10)

obviously the stuff above is not going to work but what would?, examples are appreciated,

edit: and I want to crop it before I draw it

thank you.

  • possible duplicate of [getting part of an image with javascript](http://stackoverflow.com/q/2574742/4454454) – MaxZoom Sep 08 '15 at 21:51
  • Read the Canvas documentation on MDN, I’m sure you’ll find a function that looks like it draws part of an image there. – Sebastian Simon Sep 08 '15 at 21:52
  • my question is making a image variable that is part of an image so i don't have to crop it in canvas – right over left Sep 08 '15 at 21:52
  • You have it all explained here: http://stackoverflow.com/questions/25463416/split-base64-image-into-parts (with just a couple of tweaks you can retrieve the needed part of the org image as a separate image) – Roko C. Buljan Sep 08 '15 at 21:55
  • Yeah, you can crop it before you draw it. Create an image object with `new Image()`, set the source, and when the image loads, you can use `drawImage` to draw part of it. – Sebastian Simon Sep 08 '15 at 21:55

1 Answers1

3

How to make an image from another.

// img1 is the first img    
var canvas = document.createElement("canvas"); 
canvas.width = 10;  // size of new image
canvas.height = 10;
var ctx = canvas.getContext("2d");      // get the context
// draw part of the first image onto the new canvas
ctx.drawImage(img1,0,0,10,10,0,0,10,10);            
// create a new image    
var imgNew = new Image();
// set the src from the canvas 
imgNew.src = canvas.toDataURL();
Blindman67
  • 51,134
  • 11
  • 73
  • 136
  • This is a duplicate question, but still, upvote because you've given a nice, concise version of the duplicate answer. – markE Sep 09 '15 at 03:07