ImageConstructor.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibWeb/Bindings/HTMLImageElementPrototype.h>
  7. #include <LibWeb/Bindings/HTMLImageElementWrapper.h>
  8. #include <LibWeb/Bindings/ImageConstructor.h>
  9. #include <LibWeb/Bindings/NodeWrapperFactory.h>
  10. #include <LibWeb/DOM/ElementFactory.h>
  11. #include <LibWeb/DOM/Window.h>
  12. #include <LibWeb/Namespace.h>
  13. namespace Web::Bindings {
  14. ImageConstructor::ImageConstructor(JS::GlobalObject& global_object)
  15. : NativeFunction(*global_object.function_prototype())
  16. {
  17. }
  18. void ImageConstructor::initialize(JS::GlobalObject& global_object)
  19. {
  20. auto& vm = this->vm();
  21. auto& window = static_cast<WindowObject&>(global_object);
  22. NativeFunction::initialize(global_object);
  23. define_direct_property(vm.names.prototype, &window.ensure_web_prototype<HTMLImageElementPrototype>("HTMLImageElement"), 0);
  24. define_direct_property(vm.names.length, JS::Value(0), JS::Attribute::Configurable);
  25. }
  26. ImageConstructor::~ImageConstructor()
  27. {
  28. }
  29. JS::Value ImageConstructor::call()
  30. {
  31. vm().throw_exception<JS::TypeError>(global_object(), JS::ErrorType::ConstructorWithoutNew, "Image");
  32. return {};
  33. }
  34. // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-image
  35. JS::Value ImageConstructor::construct(FunctionObject&)
  36. {
  37. auto& window = static_cast<WindowObject&>(global_object());
  38. auto& document = window.impl().document();
  39. auto image_element = DOM::create_element(document, HTML::TagNames::img, Namespace::HTML);
  40. if (vm().argument_count() > 0) {
  41. u32 width = vm().argument(0).to_u32(global_object());
  42. if (vm().exception())
  43. return {};
  44. image_element->set_attribute(HTML::AttributeNames::width, String::formatted("{}", width));
  45. }
  46. if (vm().argument_count() > 1) {
  47. u32 height = vm().argument(1).to_u32(global_object());
  48. if (vm().exception())
  49. return {};
  50. image_element->set_attribute(HTML::AttributeNames::height, String::formatted("{}", height));
  51. }
  52. return wrap(global_object(), image_element);
  53. }
  54. }