Wrapping a div around an image - How to make the div behave like the original image
Hi everyone! I have this code, which I inject into html pages and run for every image:
- var _createImageColorPicker = function(widget) {
- // store 2D context in widget for later access
- widget.ctx = null;
- // rgb
- widget.color = [0, 0, 0];
- // create additional DOM elements.
- widget.$canvas = $('<canvas class="ImageColorPickerCanvas"></canvas>');
- // add them to the DOM
- widget.element.wrap('<div class="ImageColorPickerWrapper"></div>');
- widget.$wrapper = widget.element.parent();
- widget.$wrapper.append(widget.$canvas);
- widget.ctx = widget.$canvas.get(0).getContext('2d');
- // draw the image in the canvas
- var img = new Image();
- img.src = widget.element.attr("src");
- widget.$canvas.attr("width", img.width);
- widget.$canvas.attr("height", img.height);
- widget.ctx.drawImage(img, 0, 0);
For every image in the page, the code creates a canvas and a div and draws the image inside the canvas. I need the canvas because I need access to the RGB data of the image.
However, there is a drawback to this: the div that has been wrapped around the image has different alignment properties, floating properties and potentially even size than the image, then it messes up the layout of the page.
Is there a way to fix this? I have though of two options:
1) Avoid creating a div: is it possible to get access to the data in the canvas without appending a div to the page?
2) Make the div inherit the css properties (size, floating, etc...) of the image it contains.
I'm a total beginner in jQuery and it would be great if someone could give me a little help about how to do either of these options (or a third one, if there is a better one)
Best
ZapoTeX